package com.zyf.pattern.singleton.register;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册登记式单例，每使用一次，都会往固定的的容器中去注册，并且将使用过的对象进行缓存
 * create by yifeng
 */
public class RegisterMap {

    private RegisterMap () {

    }

//    private static Map<String, Object> register = new HashMap<>();// 线程不安全的写法
    private static Map<String, Object> register = new ConcurrentHashMap<>(); // 线程安全的写法

    public static RegisterMap getInstance(String name) {
        if (name == null) {
            name = RegisterMap.class.getName();
        }

        if (register.get(name) == null) {
            try {
                register.put(name, new RegisterMap());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return (RegisterMap) register.get(name);
    }

}
